package com.tencent.wxcloudrun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencent.wxcloudrun.controller.AdminUser.*;
import com.tencent.wxcloudrun.model.AdminUser;
import com.tencent.wxcloudrun.response.AppException;
import com.tencent.wxcloudrun.response.ErrorCodeMsgEnum;
import com.tencent.wxcloudrun.service.AdminUserService;
import com.tencent.wxcloudrun.mapper.AdminUserMapper;
import com.tencent.wxcloudrun.utils.ThreadLocalTool;
import com.tencent.wxcloudrun.utils.Tools;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sts.v20180813.StsClient;
import com.tencentcloudapi.sts.v20180813.models.GetFederationTokenRequest;
import com.tencentcloudapi.sts.v20180813.models.GetFederationTokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * @author 吴海涛
 * @description 针对表【admin_user】的数据库操作Service实现
 * @createDate 2023-11-30 16:00:46
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser>
        implements AdminUserService {
    @Autowired
    AdminUserMapper adminUserMapper;

    public AdminUser login(LoginData loginData) throws NoSuchAlgorithmException {
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUser::getMobile, loginData.getMobile());
        AdminUser adminUser = adminUserMapper.selectOne(queryWrapper);

        if (adminUser == null) {
            throw new AppException(ErrorCodeMsgEnum.LOGIN_ERROR);
        }
        String password = Tools.encryptPassword(adminUser.getPassword());
        if (!adminUser.getPassword().equals(password)) {
            throw new AppException(ErrorCodeMsgEnum.LOGIN_ERROR);
        }

        return adminUser;
    }

    public HashMap<String, Object> getResAdminUser(AdminUser adminUser) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("mobile", adminUser.getMobile());
        return map;
    }


    @Override
    public Boolean resetMyPwd(ResetMyPwdData resetMyPwdData) throws NoSuchAlgorithmException {
        AdminUser user = ThreadLocalTool.getUser();
        String pwdDB = user.getPassword();
        String pwdOld = Tools.encryptPassword(resetMyPwdData.getOldPwd());


        if (!pwdDB.equals(pwdOld)) {
            throw new AppException(ErrorCodeMsgEnum.LOGIN_ERROR);
        }

//        更新---------------------
        AdminUser adminUser = new AdminUser();
        adminUser.setAdminUserId(user.getAdminUserId());
        adminUser.setPassword(Tools.encryptPassword(resetMyPwdData.getNewPwd()));

        int res = adminUserMapper.updateById(adminUser);
        return res > 0;
    }

    @Override
    public Boolean resetOnePwd(ResetOnePwdData resetOnePwdData) throws NoSuchAlgorithmException {
        AdminUser adminUser = new AdminUser();
        adminUser.setAdminUserId(resetOnePwdData.getUserId());
        adminUser.setPassword(Tools.getInitPwd());

        int res = adminUserMapper.updateById(adminUser);
        return res > 0;
    }

    @Override
    public Boolean updateMyInfo(UpdateMyInfoData updateMyInfoData) {
        AdminUser adminUser = new AdminUser();
        adminUser.setAdminUserId(ThreadLocalTool.getUser().getAdminUserId());
        adminUser.setMobile(updateMyInfoData.getMobile());
        adminUser.setTrueName(updateMyInfoData.getTrueName());

        int res = adminUserMapper.updateById(adminUser);
        return res > 0;
    }

    @Override
    public Boolean updateOneInfo(UpdateOneInfoData updateOneInfoData) {
        AdminUser adminUser = new AdminUser();
        adminUser.setAdminUserId(updateOneInfoData.getUserId());
        adminUser.setTrueName(updateOneInfoData.getTrueName());
        adminUser.setMobile(updateOneInfoData.getMobile());
        adminUser.setShopId(updateOneInfoData.getShopId());
        adminUser.setRoleIds(updateOneInfoData.getRoleIds());

        int res = adminUserMapper.updateById(adminUser);
        return res > 0;
    }


    public HashMap getCosTempToken() {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Properties properties = new Properties();
            File configFile = new File("local.properties");
            properties.load(new FileInputStream(configFile));

            Credential cred = new Credential(properties.getProperty("SecretId"), properties.getProperty("SecretKey"));
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sts.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            StsClient client = new StsClient(cred, properties.getProperty("Region"), clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            GetFederationTokenRequest req = new GetFederationTokenRequest();
            req.setName("GetFederationToken");
            req.setPolicy("%7B%22statement%22%3A%5B%7B%22action%22%3A%5B%22name%2Fcos%3AHeadBucket%22%2C%22name%2Fcos%3AGetObject%22%2C%22name%2Fcos%3AHeadObject%22%2C%22name%2Fcos%3AOptionsObject%22%2C%22name%2Fcos%3APutObject%22%2C%22name%2Fcos%3APostObject%22%2C%22name%2Fcos%3ADeleteObject%22%2C%22name%2Fcos%3AInitiateMultipartUpload%22%2C%22name%2Fcos%3AUploadPart%22%2C%22name%2Fcos%3ACompleteMultipartUpload%22%2C%22name%2Fcos%3AAbortMultipartUpload%22%5D%2C%22effect%22%3A%22Allow%22%2C%22resource%22%3A%5B%22qcs%3A%3Acos%3Aap-beijing%3Auid%2F1257288972%3Asjz-1-1257288972%2Fgoods_img%2F*%22%5D%7D%5D%2C%22version%22%3A%222.0%22%7D");
            // 返回的resp是一个GetFederationTokenResponse的实例，与请求对象对应
            GetFederationTokenResponse resp = client.GetFederationToken(req);

            HashMap res = new HashMap();
            res.put("TmpSecretId", resp.getCredentials().getTmpSecretId());
            res.put("TmpSecretKey", resp.getCredentials().getTmpSecretKey());
            res.put("SecurityToken", resp.getCredentials().getToken());
            res.put("StartTime", Math.floor(ThreadLocalTool.getTime() / 1000));
            res.put("ExpiredTime", resp.getExpiredTime());
            return res;
            // 输出json格式的字符串回包
//            System.out.println(GetFederationTokenResponse.toJsonString(resp));
        } catch (Exception e) {
            throw new AppException(ErrorCodeMsgEnum.WX_COS_ERROR);
        }
    }

    @Override
    public Page getAdminUserList(Integer pageNum, Integer pageSize) {
        Page<AdminUser> page = new Page<>(pageNum, pageSize);
        adminUserMapper.selectPage(page, null);
        return page;
    }
}




